/**
 * Created by dllo on 16/8/29.
 */



var timer=null;
var timer123=null;
var y= 1;
var buer=true;
var speed=0;
var fenshu=0;
var time123=30;
var enemys=[];
var enemys2=[];
var kongzhi=2;
var sudu=0;
var ac=2;
var canvas=document.querySelector(".canvas");
var ctx=canvas.getContext("2d");
var SCREEN_WIDTH = document.documentElement.clientWidth;
var SCREEN_HEIGHT = document.documentElement.clientHeight;
canvas.width = SCREEN_WIDTH;
canvas.height = SCREEN_HEIGHT;
$(function () {
    $(".guize").on("touchstart",function () {
        $(".guize1").css("display","block");
        $(".b1").css("display","none");
        $(".page_youxi").css("display","block");
        $(".close").css("display","block")
    });
    $(".close").on("touchstart",function () {
        $(".guize1").css("display","none");
        $(".b1").css("display","block");
        $(".page_youxi").css("display","none");
        $(".close").css("display","none")
    });
    $(".tiaozhan").on("touchstart",function () {
        $(".wrap").css("display","none");
        $(".begin").css("display","block");
        timer= setInterval(function () {
            if(y){
                $(".kaishi").fadeOut();
                y=0
            }else{
                $(".kaishi").fadeIn();
                y=1
            }
        },500)
    })
});
$(".kaishi").on("touchstart",function () {
    $(".begin").css("display","none");
    clearInterval(timer);
    loading({
        background:"img/shaidao.png",
        car1:"img/qiche.png",
        car2:"img/jiashuqiche.png",
        bullet1:"img/zhangai.png",
        bullet2:"img/zhangai1.png",
        bullet3:"img/zhangai2.png",
        bullet4:"img/zhangai3.png",
        saidao:"img/qipaoxian.png"
    },{
        complete:main

    });
    $(".div1").css("display","block")
});
//随机函数
function rand(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}
//加载完图片以后进行的函数
function main (obj) {

    //清除画布
    ctx.clearRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    //背景对象
    var bgImg = obj.background;
    var bgimg = {
        img: bgImg,
        w: bgImg.width,
        h: bgImg.height,
        x: 0,
        y: 0
    };
    //汽车对象
    var car1Img = obj.car1;
    var carimg = {
        img: car1Img,
        w: car1Img.width /2,
        h: car1Img.height /2,
        x: SCREEN_WIDTH / 2 - car1Img.width / 4,
        y: SCREEN_HEIGHT - car1Img.height * 1.5+85
    };
    //赛道对象
    var dao=obj.saidao;
    var sai={
        img:dao,
        w: dao.width/1.3 ,
        h: dao.height/1.3,
        x:0,
        y: SCREEN_HEIGHT*0.62
    };
    //障碍种类
    var zhangaiImg1=obj.bullet1;
    var zhangaiImg2=obj.bullet2;
    var zhangaiImg3=obj.bullet3;
    var zhangaiImg4=obj.bullet4;
    //障碍物构造函数
    function Enemy () {
        this.img=zhangaiImg1;
        this.w=zhangaiImg1.width/2;
        this.h=zhangaiImg1.height/2;
        this.x=rand(40,SCREEN_WIDTH-27-zhangaiImg1.width);
        this.y=-this.h;
        this.type=1;
    }
    Enemy.prototype.draw = function () {
        ctx.drawImage(this.img,this.x,this.y,this.w,this.h);
    };

    Enemy.prototype.move = function () {
        this.y += ac;
    };
    Enemy.prototype.canClear = function () {
        if (this.y>=SCREEN_HEIGHT){
            return true;
        }else{
            return false;
        }
    };
    function checkP(obj1,obj2){
        if(Math.abs(obj1.x + obj1.w / 2 - (obj2.x + obj2.w / 2)) <= obj1.w / 2 + obj2.w / 2 && Math.abs(obj1.y + obj1.h / 2 - (obj2.y + obj2.h / 2)) <= obj1.h / 2 + obj2.h / 2) {
            (obj1.x)
            return true;
        } else {
            return false;
        }
    }
    Enemy.prototype.changeType = function(type) {
        this.type = type;
        switch(this.type) {
            case 1:
                this.img=zhangaiImg1;
                this.w=zhangaiImg1.width/2;
                this.h=zhangaiImg1.height/2;
                this.x=rand(40,SCREEN_WIDTH-27-zhangaiImg1.width);
                this.y=-this.h;
                break;
            case 2:
                this.img = zhangaiImg2;
                this.w = zhangaiImg2.width/2;
                this.h = zhangaiImg2.height/2;
                this.x = rand(40,SCREEN_WIDTH-27-zhangaiImg2.width);
                this.y = -this.h;
                break;
            case 3:
                this.img = zhangaiImg3;
                this.w = zhangaiImg3.width/2;
                this.h = zhangaiImg3.height/2;
                this.x = rand(40,SCREEN_WIDTH-27-zhangaiImg3.width);
                this.y = -this.h;
                break;
            case 4:
                this.img = zhangaiImg4;
                this.w = zhangaiImg4.width/2;
                this.h = zhangaiImg4.height/2;
                this.x = rand(40,SCREEN_WIDTH-27-zhangaiImg4.width);
                this.y = -this.h;
                break;
        }
    };
    ctx.drawImage(obj.background,0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
    ctx.drawImage(obj.saidao,sai.x,sai.y,sai.w,sai.h)
    ctx.drawImage(carimg.img,carimg.x,carimg.y,carimg.w,carimg.h)
    //画画
    function drawAll() {
        ctx.clearRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        speed+=kongzhi;
        sudu++;
        //判断加速
        $(".jiashuqi").on("touchstart",function () {
            $(".jiashuqi").css("display","none");
            carimg.img=obj.car2;
            kongzhi=4;
            ac=4;
            $(".jianshuqi").on("touchstart",function () {
                carimg.img=obj.car1;
                $(".jiashuqi").css("display","block");
                kongzhi=2;
                ac=2;
            })

        });
        //画背景
        ctx.drawImage(obj.background,0,speed,SCREEN_WIDTH,SCREEN_HEIGHT);
        ctx.drawImage(obj.background,0,speed - SCREEN_HEIGHT,SCREEN_WIDTH,SCREEN_HEIGHT);
        //画赛道
        ctx.drawImage(obj.saidao,sai.x,sai.y+speed,sai.w,sai.h);
        ////画障碍和删除多余的障碍
        if (sudu%66==0){
            var enemy = new Enemy();
            if (sudu%396 == 0){
                enemy.changeType(2);
            }else if (sudu%660 ==0){
                enemy.changeType(3);
            }else if (sudu%924 ==0){
                enemy.changeType(4);
            }
            enemys.push(enemy);
            enemys2.push(enemy);
        }



        //删除出屏幕的障碍物
        for(var i = 0;i< enemys.length;i++) {
            var enemy = enemys[i];
            //判断撞车
            if(checkP(carimg,enemy)){
                clearInterval(timer123);
                $(".canvas").css("display","none");
                $(".div1").css("display","none");
                buer=false;
                console.log(fenshu);

                if (fenshu>10){
                    $("#pageEnd_success").show();
                    $(".fenshu123").text(fenshu);
                }else{
                    $("#pageEnd_fail").show();
                    $(".shibaifenshu").text(fenshu)

                }

                $.ajax({
                    url:"car_api.php",
                    type:"get",
                    dataType:"jsonp",
                    data:{
                        score:fenshu,
                        openid:openid,
                        type:"number"
                    },
                    success:function (data) {
                        $("#percent").html(data["rank3"]);
                    }
                })
            }
            if (enemy.canClear()) {
                enemys.splice(i, 1);
                i--;
            }
            enemy.draw();
            enemy.move();
        }
        //计数
        for(var k = 0;k< enemys2.length;k++){
            var enemy2 = enemys2[k];
            if (enemy2.y>carimg.y+carimg.h){
                enemys2.splice(k,1);
                fenshu++;
            }
        }
        //保持背景屏幕连续滚动
        if (speed>=SCREEN_HEIGHT){
            sai.y=SCREEN_HEIGHT;
            speed=0;
        }
        //画汽车
        ctx.drawImage(carimg.img,carimg.x,carimg.y,carimg.w,carimg.h);
        //判断运行window
        if(buer){
            window.requestAnimationFrame(drawAll);
        }

    }
    function acac() {
        //控制红绿灯
        setTimeout(function () {
            $(".ding").css("display","none");
        },1000);
        setTimeout(function () {
            $(".hongding").css("display","none");
        },2000);
        setTimeout(function () {
            $(".huangding").css("display","none");
        },3000);
        setTimeout(function () {
            //画画
            drawAll();
            //倒计时
            timer123=setInterval(function () {
                time123--;
                $(".daojishi").text(time123);
                if(time123<10){
                    $(".daojishi").text("0"+time123);
                }
                if (time123==0){
                    clearInterval(timer123);
                    buer=false;
                    if (fenshu>10){
                        $("#pageEnd_success").show();
                        $(".fenshu123").text(fenshu);
                    }else{
                        $("#pageEnd_fail").show();
                        $(".shibaifenshu").text(fenshu)

                    }
                    $(".canvas").css("display","none");
                    $(".div1").css("display","none");
                    $.ajax({
                        url:"car_api.php",
                        type:"get",
                        dataType:"json",
                        data:{
                            score:fenshu,
                            openid:openid,
                            type:"number"
                        },
                        success:function (data) {
                            $("#percent").html(data["rank3"]);
                        }
                    })
                }
            },1000);
            $(".lvding").fadeOut(500);
            $(".start").fadeOut(500);
            //控制汽车
            var zuoyou=10;
            $(".anniuz").on("touchstart",function (event) {
                carimg.x -=zuoyou;
                event.preventDefault();
                var timer =setInterval(function () {
                    carimg.x -=1
                },20);
                $(".anniuz").on("touchend",function () {
                    clearInterval(timer);
                    event.preventDefault();
                })
            });
            $(".anniuy").on("touchstart",function (event) {
                carimg.x +=zuoyou;
                event.preventDefault();
                var timer1 =setInterval(function () {
                    carimg.x +=1
                },20);
                $(".anniuy").on("touchend",function () {
                    clearInterval(timer1);
                    event.preventDefault();
                })
            });
        },4000)
    }
   acac();
    $(".againGo").on("touchstart",function () {
        $(".ding").css("display","block");
        $(".hongding").css("display","block");
        $(".start").css("display","block")
        $(".huangding").css("display","block");
        $(".lvding").css("display","block");
        $(".canvas").css("display","block");
        $(".div1").css("display","block");
        $("#pageEnd_fail").hide();
         timer=null;
        timer123=null;
        y= 1;
       speed=0;
        fenshu=0;
       time123=30;
        enemys=[];
        enemys2=[];
        kongzhi=2;
        sudu=0;
        ac=2;
        buer=true;
        $(".jiashuqi").css("display","block")

        sai.img=dao;
            sai.w=dao.width/1.3;
            sai.h=dao.height/1.3;
        sai.x=0;
        sai.y=SCREEN_HEIGHT*0.62;
        carimg.img=obj.car1;
        carimg.w=car1Img.width /2;
        carimg.h=car1Img.height /2;
        carimg.x=SCREEN_WIDTH / 2 - car1Img.width / 4;
        carimg.y=SCREEN_HEIGHT - car1Img.height * 1.5+85;
        $(".daojishi").text(time123);
        ctx.drawImage(obj.background,0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
        ctx.drawImage(obj.saidao,sai.x,sai.y,sai.w,sai.h);
        ctx.drawImage(carimg.img,carimg.x,carimg.y,carimg.w,carimg.h);
        acac();
    })
}

var k=0;
var speedr = 0;
var json={"北京": ["西城", "东城", "崇文", "宣武", "朝阳", "海淀", "丰台", "石景山", "门头沟", "房山", "通州", "顺义", "大兴", "昌平", "平谷", "怀柔", "密云", "延庆"] ,
    "天津": ["青羊", "河东", "河西", "南开", "河北", "红桥", "塘沽", "汉沽", "大港", "东丽", "西青", "北辰", "津南", "武清", "宝坻", "静海", "宁河", "蓟县", "开发区"] ,
    "河北": ["石家庄", "秦皇岛", "廊坊", "保定", "邯郸", "唐山", "邢台", "衡水", "张家口", "承德", "沧州", "衡水"] ,
    "山西": ["太原", "大同", "长治", "晋中", "阳泉", "朔州", "运城", "临汾"] ,
    "内蒙古": ["呼和浩特", "赤峰", "通辽", "锡林郭勒", "兴安"] ,
    "辽宁": ["大连", "沈阳", "鞍山", "抚顺", "营口", "锦州", "丹东", "朝阳", "辽阳", "阜新", "铁岭", "盘锦", "本溪", "葫芦岛"] ,
    "吉林": ["长春", "吉林", "四平", "辽源", "通化", "延吉", "白城", "辽源", "松原", "临江", "珲春"] ,
    "黑龙江": ["哈尔滨", "齐齐哈尔", "大庆", "牡丹江", "鹤岗", "佳木斯", "绥化"] ,
    "上海": ["浦东", "杨浦", "徐汇", "静安", "卢湾", "黄浦", "普陀", "闸北", "虹口", "长宁", "宝山", "闵行", "嘉定", "金山", "松江", "青浦", "崇明", "奉贤", "南汇"] ,
    "江苏": ["南京", "苏州", "无锡", "常州", "扬州", "徐州", "南通", "镇江", "泰州", "淮安", "连云港", "宿迁", "盐城", "淮阴", "沐阳", "张家港"] ,
    "浙江": ["杭州", "金华", "宁波", "温州", "嘉兴", "绍兴", "丽水", "湖州", "台州", "舟山", "衢州"] ,
    "安徽": ["合肥", "马鞍山", "蚌埠", "黄山", "芜湖", "淮南", "铜陵", "阜阳", "宣城", "安庆"] ,
    "福建": ["福州", "厦门", "泉州", "漳州", "南平", "龙岩", "莆田", "三明", "宁德"] ,
    "江西": ["南昌", "景德镇", "上饶", "萍乡", "九江", "吉安", "宜春", "鹰潭", "新余", "赣州"] ,
    "山东": ["青岛", "济南", "淄博", "烟台", "泰安", "临沂", "日照", "德州", "威海", "东营", "荷泽", "济宁", "潍坊", "枣庄", "聊城"] ,
    "河南": ["郑州", "洛阳", "开封", "平顶山", "濮阳", "安阳", "许昌", "南阳", "信阳", "周口", "新乡", "焦作", "三门峡", "商丘"] ,
    "湖北": ["武汉", "襄樊", "孝感", "十堰", "荆州", "黄石", "宜昌", "黄冈", "恩施", "鄂州", "江汉", "随枣", "荆沙", "咸宁"] ,
    "湖南": ["长沙", "湘潭", "岳阳", "株洲", "怀化", "永州", "益阳", "张家界", "常德", "衡阳", "湘西", "邵阳", "娄底", "郴州"] ,
    "广东": ["广州", "深圳", "东莞", "佛山", "珠海", "汕头", "韶关", "江门", "梅州", "揭阳", "中山", "河源", "惠州", "茂名", "湛江", "阳江", "潮州", "云浮", "汕尾", "潮阳", "肇庆", "顺德", "清远"] ,
    "广西": ["南宁", "桂林", "柳州", "梧州", "来宾", "贵港", "玉林", "贺州"] ,
    "海南": ["海口", "三亚"] ,
    "重庆": ["渝中", "大渡口", "江北", "沙坪坝", "九龙坡", "南岸", "北碚", "万盛", "双桥", "渝北", "巴南", "万州", "涪陵", "黔江", "长寿"] ,
    "四川": ["成都", "达州", "南充", "乐山", "绵阳", "德阳", "内江", "遂宁", "宜宾", "巴中", "自贡", "康定", "攀枝花"] ,
    "贵州": ["贵阳", "遵义", "安顺", "黔西南", "都匀"] ,
    "云南": ["昆明", "丽江", "昭通", "玉溪", "临沧", "文山", "红河", "楚雄", "大理"] ,
    "西藏": ["拉萨", "林芝", "日喀则", "昌都"] ,
    "陕西": ["西安", "咸阳", "延安", "汉中", "榆林", "商南", "略阳", "宜君", "麟游", "白河"] ,
    "甘肃": ["兰州", "金昌", "天水", "武威", "张掖", "平凉", "酒泉"] ,
    "青海": ["黄南", "海南", "西宁", "海东", "海西", "海北", "果洛", "玉树"] ,
    "宁夏": ["银川", "吴忠"] ,
    "新疆": ["乌鲁木齐", "哈密", "喀什", "巴音郭楞", "昌吉", "伊犁", "阿勒泰", "克拉玛依", "博尔塔拉"] ,
    "香港": ["中西区", "湾仔区", "东区", "南区", "九龙-油尖旺区", "九龙-深水埗区", "九龙-九龙城区", "九龙-黄大仙区", "九龙-观塘区", "新界-北区", "新界-大埔区", "新界-沙田区", "新界-西贡区", "新界-荃湾区", "新界-屯门区", "新界-元朗区", "新界-葵青区", "新界-离岛区"] ,
    "澳门": ["花地玛堂区", "圣安多尼堂区", "大堂区", "望德堂区", "风顺堂区", "嘉模堂区", "圣方济各堂区", "路氹城"]};
var provSelect = document.getElementById("province");
var citySelect = document.getElementById("city");
for(key in json){
    var option = document.createElement("option");
    option.innerHTML = key;
    provSelect.appendChild(option);
}

provSelect.onchange = function () {
    console.log(this.selectedIndex);
    console.log(this.options[this.selectedIndex].innerHTML);
    //清空city
    citySelect.innerHTML = "";
    var citys = json[this.options[this.selectedIndex].innerHTML];
    console.log(citys);
    for(var i = 0; i < citys.length; i++){
        var option = document.createElement("option");
        option.innerHTML = citys[i];
        citySelect.appendChild(option);
    }
};


$(function () {

        //分享邀请
        $(".invitation_2").on("touchstart",function () {
            $("#pageShare").show();
            //这里可能存在问题???
            $("#pageShare").on("touchstart",function () {
                //$("#pageShare").hide();
                //向后台发送请求,判断数据库里有没有人点晋级
                $.ajax({
                    url:"car_api.php",
                    type:"get",
                    dataType:"json",
                    data:{
                        type:"gotup",
                        openid:openid
                    },
                    success:function (data) {
                        console.log(data);
                        if(data["up"]>0){
                            $("#levelUp_success").show();
                            setTimeout(function () {
                                $("#levelUp_success").hide();
                                //抽奖
                                $(".finger").on("touchstart",function () {
                                    $.ajax({
                                        url:"car_api.php",
                                        type:"get",
                                        dataType:"json",
                                        data:{
                                            type:"randomPrize",
                                            openid:openid
                                        },
                                        success:function (data) {
                                            console.log(data);
                                            console.log(data["prizenum"]);
                                            num = data["prizenum"];
                                        },
                                        complete:function (a,b) {
                                            console.log(b);
                                        }
                                    });


                                    clearInterval(timer1);
                                    var timer1=setInterval(function () {
                                        k++;
                                        $(".turnDish_1").css({
                                            transform:"rotateZ("+k+"deg)"
                                        });
                                        if(k==720){
                                            clearInterval(timer1);
                                            var timer2=setInterval(function () {
                                                speedr++;
                                                $(".turnDish_1").css({
                                                    transform:"rotateZ("+speedr+"deg)"
                                                });
                                                if (speedr==num*30){
                                                    clearInterval(timer2);
                                                    setTimeout(function (){
                                                        $("#random_prize").hide();
                                                        $("#random_prize_suc").show();
                                                        if (num==1||num==7||num==10){
                                                            //抽奖失败
                                                            $("#random_prize_suc").hide();
                                                            $(".gotPrizeFail").show();
                                                        }else{
                                                            //抽奖成功
                                                            $(".prizeBook_wrap").empty();
                                                            var newImg=$("<img_pageEnd>");
                                                            newImg.attr("src","img_pageEnd/prize_" + num + ".png");
                                                            newImg.addClass("prizeBook");
                                                            $(".prizeBook_wrap").append(newImg);
                                                            $(".writePersonMessage").on("touchstart",function () {
                                                                $("#random_prize_suc").hide();
                                                                $("#register_prize_message").show();
                                                                //抽奖成功,填写领奖注册信息,提交
                                                                $(".fillDone").on("touchstart",function () {
                                                                    $.ajax({
                                                                        url:"car_api.php",
                                                                        type:"get",
                                                                        dataType:"json",
                                                                        data:{
                                                                            type:"register",
                                                                            openid:openid,
                                                                            username:$("#username").val(),
                                                                            tel:$("#tel").val(),
                                                                            province:$("#province").val(),
                                                                            city:$("#city").val(),
                                                                            address:$("#address").val()
                                                                        },
                                                                        success:function (data) {
                                                                            console.log(data);
                                                                        },
                                                                        complete:function (a,b) {
                                                                            console.log(b);
                                                                        }
                                                                    });
                                                                    $("#register_prize_message").hide();
                                                                    $(".messageSubmitSuc").show();
                                                                })
                                                            })
                                                        }
                                                    },1000)
                                                }
                                            },10)
                                        }
                                    },10);
                                })
                            },1000)
                        }
                    }
                });
                //向后台发送请求,判断数据库里有没有人点你丫太差
                $.ajax({
                    url:"car_api.php",
                    type:"get",
                    dataType:"json",
                    data:{
                        type:"gotdown",
                        openid:openid
                    },
                    success:function (data) {
                        console.log(data);
                        if (data["down"]>0){
                            $("#no_friends_levelUpYou").show();
                            setTimeout(function () {
                                $("#no_friends_levelUpYou").hide();
                                $("#you_are_out").show();
                            },500)
                        }
                    }

                })

            })
        });
    //排行榜
    $(".rankList").on("touchstart",function () {
        $("#pageRank").show();
        $.ajax({
            url:"car_api.php",
            type:"get",
            dataType:"json",
            data:{
                type:"paihang"
            },
            success:function (data) {
               for(var i=0;i<data.length;i++){
                    $("#rank_list li span").eq(i*3+1).text(data[i][score]);
                   $("#rank_list li span").eq(i*3+2).text(data[i][nickname])
               }
            }
        });
        $(".bg_rank").on("touchstart",function () {
            $("#pageRank").hide();
            $("#pageEnd_success").show();
        })
    });

 

});